"""
Case Type   : 资源池化-多节点写入
Case Name   : 备机执行简单只读查询，备机本地执行，不转发给主机
Create At   : 2024/04/30
Owner       : zhengxue
Description :
    1.修改enable_remote_execute参数值为on
    2.主机创建表
    3.备机执行简单只读查询
    4.备机查看日志打印
    5.环境清理，恢复参数
Expect      :
    1.修改成功
    2.创建成功
    3.查询成功
    4.不转发给主机
    5.环境清理成功，恢复参数成功
Pre-operation:
    1.在conf/macro.yml中配置PG_LOG_PATH为数据库pg_log目录,对应用例中的macro.PG_LOG_PATH
History     :
    1、2024-04-30 创建
"""
import os
import time
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant

Primary_SH = CommonSH('PrimaryDbUser')

class MultiNodeWrite(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.std_node = Node('Standby1DbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.std_sh = CommonSH('Standby1DbUser')
        self.common = Common('Standby1DbUser')
        self.constant = Constant()
        self.table_name = 't_write_transfer_case0006'
        self.new_log_dir = os.path.join(macro.PG_LOG_PATH,
                                        'pg_log_write_transfer_case0006')                               
        self.enable_remote_execute = 'enable_remote_execute'
        self.log_statement = 'log_statement'
        self.log_directory = 'log_directory'
        self.remote_excute_default = self.common.show_param(
            self.enable_remote_execute)
        self.log_statement_default = self.common.show_param(self.log_statement)
        self.log_dir_default = self.common.show_param(self.log_directory)
        shell_cmd = f"rm -rf {self.new_log_dir}"
        self.log.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.std_node, shell_cmd)
        self.assertEquals('', shell_msg, '删除目录失败')

    def test_multi_node_write(self):
        step1 = "-----step1:修改enable_remote_execute参数值为on;expect:修改成功-----"
        self.log.info(step1)
        result = self.std_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}=on')
        restart_res = self.std_sh.restart_db_cluster()
        self.assertTrue(restart_res, f'执行失败:{step1}')
        status = Primary_SH.exec_cm_ctl(mode='query', param='-Cv')
        self.log.info(status)
        result = self.std_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_statement}=all')
        show_log_statement = self.common.show_param(self.log_statement)
        self.assertEquals(show_log_statement, 'all', f'执行失败:{step1}')
        self.assertTrue(result, f'执行失败:{step1}')
        result = self.std_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory}='{self.new_log_dir}'", single=True)
        self.assertTrue(result, f'执行失败:{step1}')

        step2 = "-----step2:主机创建表;expect:创建成功-----"
        self.log.info(step2)
        create_tb = f"drop table if exists {self.table_name};" \
                    f"create table {self.table_name}(id int);" \
                    f"insert into {self.table_name} " \
                    f"values(generate_series(1,10));"
        create_msg = self.pri_sh.execut_db_sql(create_tb)
        self.log.info(create_msg)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS,
                      create_msg, f'执行失败:{step2}')
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS,
                      create_msg, f'执行失败:{step2}')
        self.assertIn(self.constant.INSERT_SUCCESS_MSG,
                      create_msg, f'执行失败:{step2}')
        time.sleep(5)

        step3 = "-----step3:备机执行简单只读查询;expect:查询成功-----"
        self.log.info(step3)
        query_cmd = f"select * from {self.table_name};"
        query_msg = self.std_sh.execut_db_sql(query_cmd)
        self.log.info(query_msg)
        self.assertIn('(10 rows)', query_msg, f'执行失败:{step3}')

        step4 = "-----step4:备机查看日志打印;expect:不转发给主机-----"
        self.log.info(step4)
        shell_cmd = f"ls -t {self.new_log_dir}"
        self.log.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.std_node, shell_cmd)
        logfile = os.path.join(self.new_log_dir, shell_msg.split()[-1])
        self.log.info(logfile)
        shell_cmd = f"cat {logfile} "
        self.log.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.std_node, shell_cmd)
        self.log.info(shell_msg)
        self.assertIn(f'[TRACE] Q: portal=select * from '
                      f't_write_transfer_case0006;, stmt=OTHER',
                      shell_msg, f'执行失败:{step4}')

    def tearDown(self):
        step5 = "-----step5:环境清理，恢复参数;expect:环境清理成功，恢复参数成功-----"
        self.log.info(step5)
        drop_tb = f"drop table {self.table_name};"
        drop_res = self.pri_sh.execut_db_sql(drop_tb)
        self.log.info(drop_res)
        result1 = self.std_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}={self.remote_excute_default}')
        status = Primary_SH.exec_cm_ctl(mode='query', param='-Cv')
        self.log.info(status)
        status = Primary_SH.check_cluster_core_status(status, wait_times=600)
        self.log.info(status)
        restart_res = self.std_sh.restart_db_cluster()
        recovery = Primary_SH.exec_cm_ctl(mode='switchover', param='-a')
        self.log.info(recovery)
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        result2 = self.std_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_statement}={self.log_statement_default}')
        result3 = self.std_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory}='{self.log_dir_default}'", single=True)
        show_log_statement = self.common.show_param(self.log_statement)
        show_log_directory = self.common.show_param(self.log_directory)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS,
                      drop_res, f'执行失败:{step5}')
        self.assertTrue(result1, f'执行失败:{step5}')
        self.assertTrue(restart_res, f'执行失败:{step5}')
        self.assertIn(self.constant.cm_switchover_success_msg, recovery,
                      '执行失败' + step5)
        self.assertEquals(show_remote_excute, self.remote_excute_default,
                          f'执行失败:{step5}')
        self.assertTrue(result2, f'执行失败:{step5}')
        self.assertTrue(result3, f'执行失败:{step5}')
        self.assertEquals(show_log_statement, self.log_statement_default,
                          f'执行失败:{step5}')
        self.assertEquals(show_log_directory, self.log_dir_default,
                          f'执行失败:{step5}')
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
